<?php
/**
 * erp品类销量报表 (erp)
 */
namespace App\Logic\SalesReport;

use App\Models\Basics\SysPlat;
use App\Models\Inventory\Timely;
use App\Models\SalesReport\DailyCv;
use App\Models\SalesReport\DailyCva;
use App\Models\SalesReport\DailyCvs;
use App\Models\SalesReport\DailySv;
use Illuminate\Support\Facades\DB;
class DailySalesVolumeClassify
{
    public static function init(){
        try{
            DailyCv::query()->truncate(); //重置品类销量数据
            DailyCva::query()->truncate(); //重置品类下的站点销量
            DailyCvs::query()->truncate(); //重置品类下的SKU销量

            DB::beginTransaction();
            //SKU日销量统计报表
            $dsv = DailySv::query()
                ->where('classify_id','<>',0)
                ->select('plat_id','classify_id',DB::raw(self::getSumFields()))
                ->groupBy('plat_id','classify_id')
                ->get();

            $greaterThan = date('Y-m-d');
            $i = 0;
            $num = 100;
            while(true){
                if($dsv->isEmpty())break;
                $_dsv = $dsv->splice($i,$num);
                foreach($_dsv as $ds){
                    $pSkuIds = DailySv::query()
                        ->where('plat_id',$ds->plat_id)
                        ->where('classify_id',$ds->classify_id)
                        ->distinct('psku_id')
                        ->pluck('psku_id')
                        ->toArray();
                    $dailyClassifyTotal = $ds->toArray();
                    if ($ds->plat_id == SysPlat::PLAT_AMAZON) {
                        $dailyClassifyTotal['cn_instant_num'] = Timely::getClassifyInstant($pSkuIds);
                        $dailyClassifyTotal['cn_transit_num'] = Timely::getClassifyTransit($pSkuIds);
                    }else{
                        $dailyClassifyTotal['cn_instant_num'] = 0;
                        $dailyClassifyTotal['cn_transit_num'] = 0;
                    }
                    $dailyClassifyTotal['less_than'] = DailySv::SATE_REPORT_DATE;
                    $dailyClassifyTotal['greater_than'] = $greaterThan;
                    $avgSalesVolume = self::getAvgSalesVolume($ds->avg3,$ds->avg7,$ds->avg15,$ds->avg30);

                    $dailyClassifyTotal = array_merge($dailyClassifyTotal,$avgSalesVolume);
                    $cv = DailyCv::query()->updateOrCreate([
                        'plat_id' =>$ds->plat_id,
                        'classify_id' => $ds->classify_id
                    ],$dailyClassifyTotal);
                    self::initArea($cv,$ds->classify_id);
                    self::initSku($cv,$ds->classify_id);
                }
            }
            DB::commit();
        }catch (\Exception $e){
            DB::rollBack();
            report($e);
        }
    }

    /**
     * 品类（站点销量）
     * @param $cv
     * @param $classifyId
     */
    protected static function initArea($cv,$classifyId){
        $dsv = DailySv::query()
            ->where('plat_id',$cv->plat_id)
            ->where('classify_id',$classifyId)
            ->select('area_id',DB::raw(self::getSumFields()))
            ->groupBy('area_id')
            ->get();
        foreach($dsv as $ds){
            $dailyAreaTotalWhere = [];
            $dailyAreaTotalWhere['cv_id'] = $cv->id;
            $dailyAreaTotalWhere['plat_id'] = $cv->plat_id;
            $dailyAreaTotalWhere['area_id'] = $ds->area_id;
            $dailyAreaTotal = $ds->toArray();
            $avgSalesVolume = self::getAvgSalesVolume($ds->avg3,$ds->avg7,$ds->avg15,$ds->avg30);
            $dailyAreaTotal = array_merge($dailyAreaTotal,$avgSalesVolume);
            DailyCva::query()->updateOrCreate($dailyAreaTotalWhere,$dailyAreaTotal);
        }
    }

    /**
     * 品类（sku销量）
     * @param $cv
     * @param $classifyId
     */
    protected static function initSku($cv,$classifyId){
        $dsv = DailySv::query()
            ->where('plat_id',$cv->plat_id)
            ->where('classify_id',$classifyId)
            ->select('psku_id',DB::raw(self::getSumFields()))
            ->groupBy('psku_id')
            ->get();
        foreach($dsv as $ds){
            $dailySkuTotalWhere = [];
            $dailySkuTotalWhere['cv_id'] = $cv->id;
            $dailySkuTotalWhere['plat_id'] = $cv->plat_id;
            $dailySkuTotalWhere['psku_id'] = $ds->psku_id;
            $dailySkuTotal = $ds->toArray();
            if ($ds->plat_id == SysPlat::PLAT_AMAZON) {
                $dailySkuTotal['cn_instant_num'] = Timely::getInstant($ds->psku_id);
                $dailySkuTotal['cn_transit_num'] = Timely::getAreaTransit($ds->psku_id);
            }else{
                $dailySkuTotal['cn_instant_num'] = 0;
                $dailySkuTotal['cn_transit_num'] = 0;
            }
            $avgSalesVolume = self::getAvgSalesVolume($ds->avg3,$ds->avg7,$ds->avg15,$ds->avg30);
            $dailySkuTotal = array_merge($dailySkuTotal,$avgSalesVolume);
            DailyCvs::query()->updateOrCreate($dailySkuTotalWhere,$dailySkuTotal);
        }
    }

    protected static function getSumFields(){
        $headers = DailySv::headersField();
        $re = [];
        foreach ($headers as $field => $item){
            if($item['sumField']){
                $re[] = 'sum('.$field.') as '.$field;
            }else{
                continue;
            }
        }
        return implode(',',$re);
    }

    /**
     * 平均销量
     * @param $avg3
     * @param $avg7
     * @param $avg15
     * @param $avg30
     * @return array
     */
    protected static function getAvgSalesVolume($avg3,$avg7,$avg15,$avg30){
        $re = [];
        $re['sales_status'] = DailySv::getSalesStatus($avg3,$avg7,$avg15,$avg30);
        $re['avg'] = DailySv::getWeightAvg($avg3,$avg7,$avg15,$avg30,$re['sales_status']);
        return $re;
    }
}
